import 'package:flutter/material.dart';
import 'package:hx_im_plugin/hx_im_plugin.dart';
import 'package:hx_im_plugin_example/hq_im_ui/utils/im_helper.dart';
import 'package:hx_im_plugin_example/hq_im_ui/widgets/hq_common_widgets.dart';

/// 全局属性
bool isShowStatus = true;  /// 状态栏
bool isShowRecharge = true; /// 更换按钮
bool isShowBottom = true;  /// 底部按钮
bool isShowRightButton = true; /// 底部右边按钮
bool isShowDriver = true; /// 司机信息
String orderNum = '请您确认运单信息';
String statusName = '运输中';
String leftButton = '拒绝接单';
String rightButton = '确认接单';
HqOrderButtonType lbuttonType = HqOrderButtonType.RefuseOrder;
HqOrderButtonType rbuttonType = HqOrderButtonType.SureReceiveOrder;
Color statusColor = Color.fromRGBO(0, 201, 195, 1.0);

/// 自定义消息
class HQChatOrderBubble extends StatefulWidget {

  final EMCustomMessageBody body;
  final EMConversation conv;
  HQChatOrderBubble(
      this.body,
      EMConversation conversation
      ) : conv = conversation;

  @override
  _HQChatOrderBubbleState createState() => _HQChatOrderBubbleState();
}

class _HQChatOrderBubbleState extends State<HQChatOrderBubble> {

  /// 运单
  Map<String, String> _params;

  /// 运输状态：0-指派单；1-运输中；2-待结算；3-待结算未评价；4-已拒绝；5-已失效；6-转发运单；7-分享的运单
  String _status = "0";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _initParams();
  }

  @override
  void didUpdateWidget(covariant HQChatOrderBubble oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);

    _initParams();
  }

  /// 初始化参数
  _initParams() {
    if(mounted) {
      setState(() {
        if(widget.body != null) {
          _params = widget.body.params;
        }
        _status = _params["status"];
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      // margin: EdgeInsets.only(left: sWidth(32), right: sWidth(80)),
      padding: EdgeInsets.only(left: sWidth(6), top: sHeight(8), bottom: sHeight(8)),
      decoration: BoxDecoration(
        /// 圆角
        borderRadius: BorderRadius.circular(sHeight(4)),
        /// 背景
        color: Colors.white
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          /// 状态显示区
          HqOrderStatus(_params),
          /// 地图图片显示区
          HqOrderMapImageFromMessage(_params),
          /// order信息区
          HqOrderFromMessage(_params, widget.conv),
          /// 按钮区
          HqOrderButtonFromMessage(_params, widget.conv)
        ],
      ),
    );
  }

}

/// 状态显示区
class HqOrderStatus extends StatefulWidget {

  final Map<String, String> params;
  HqOrderStatus(this.params);

  @override
  _HqOrderStatusState createState() => _HqOrderStatusState();
}

class _HqOrderStatusState extends State<HqOrderStatus> {

  Map<String, String> _params;
  String _num;
  /// 运输状态：0-指派单；1-运输中；2-待结算；3-待结算未评价；4-已拒绝；5-已失效；6-转发运单；7-分享的运单
  String _status;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _initParams();
  }

  @override
  void didUpdateWidget(covariant HqOrderStatus oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);

    _initParams();
  }

  _initParams() {
    if(mounted) {
      setState(() {
        if(widget.params != null) {
          _params = widget.params;
          _num = widget.params["id"];
          _status = widget.params["status"];
        }
        HqGetOrderDataForStatus(_status);
      });
    }
  }

  _setTitle() {
    String order = '请您确认运单信息';
    if(_status == '1' || _status == '2' || _status == '3') {
      order = _params['id'];
    } else if(_status == '4' || _status == '5') {
      order = '运单信息';
    } else if(_status == '6') {
      order = '我转发了一个运单';
    } else if(_status == '7') {
      order = '我分享了一个运单';
    }
    return order;
  }

  @override
  Widget build(BuildContext context) {

    return Container(
      padding: EdgeInsets.only(left: sWidth(6), bottom: sHeight(6)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(_setTitle(), style: TextStyle(
              fontSize: sFontSize(14),
              color: Color.fromRGBO(29, 32, 35, 1.0)
          ),),
          !isShowStatus ? Container() :
          Container(
            padding: EdgeInsets.fromLTRB(sWidth(7), sHeight(2), sWidth(7), sHeight(2)),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              /// 圆角
              borderRadius: BorderRadius.horizontal(left: Radius.circular(10.5)),
              /// 背景
              color: statusColor,
              /// 设置四周边框
              border: Border.all(width: 1, color: Colors.white),
            ),
            child: Text(statusName, style: TextStyle(
                fontSize: sFontSize(12),
                color: Colors.white
            ),),
          )
        ],
      ),
    );
  }
}

/// 地图图片显示区
class HqOrderMapImageFromMessage extends StatefulWidget {

  final Map<String, String> params;
  HqOrderMapImageFromMessage(this.params);

  @override
  _HqOrderMapImageFromMessageState createState() => _HqOrderMapImageFromMessageState();
}

class _HqOrderMapImageFromMessageState extends State<HqOrderMapImageFromMessage> {

  Map<String, String> _params;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _initParams();
  }

  @override
  void didUpdateWidget(covariant HqOrderMapImageFromMessage oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);

    _initParams();
  }

  _initParams() {
    if(mounted) {
      setState(() {
        if(widget.params != null) {
          _params = widget.params;
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: sWidth(6), bottom: sHeight(8), right: sWidth(6)),
      child: Stack(
        children: [
          Container(
            child: Image.asset('images/hq_chat_order_bubble_map.png'),
          ),
          Positioned(
            top: sHeight(6.5),
            left: sWidth(6),
            right: sWidth(6),
            child: Flex(
              direction: Axis.horizontal,
              children: [
                _item(false ,_params["startCity"], 'YU LIN'),
                _item(true ,_params["distance"], 'images/hq_chat_order_bubble_map_car.png'),
                _item(false, _params["endCity"], 'CHENG DU'),
              ],
            ),
          )
        ],
      ),
    );
  }

  /// order地址info
  _item(bool isHaveImage, String city, String pinyin) {
    return Expanded(
      child: isHaveImage ? Column(
        children: [
          Text(city,
            style: TextStyle(
                fontSize: sFontSize(10),
                color: Colors.white),),
          Container(
            height: sHeight(16),
            width: sWidth(53.5),
            child: Image.asset(pinyin),
          )
        ],
      ) : Column(
        children: [
          Text(city,
            style: TextStyle(
                fontSize: sFontSize(16),
                fontWeight: FontWeight.bold,
                color: Colors.white),),
          Text(pinyin, style: TextStyle(fontSize: sFontSize(10), color: Colors.white),),
        ],
      ),
    );
  }
}

/// order信息区
class HqOrderFromMessage extends StatefulWidget {

  final EMConversation conv;
  final Map<String, String> params;
  HqOrderFromMessage(this.params, EMConversation conversation) : conv = conversation;

  @override
  _HqOrderFromMessageState createState() => _HqOrderFromMessageState();
}

class _HqOrderFromMessageState extends State<HqOrderFromMessage> {

  Map<String, String> _params;
  String _status;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _initParams();
  }

  @override
  void didUpdateWidget(covariant HqOrderFromMessage oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);

    _initParams();
  }

  _initParams() {
    if(mounted) {
      setState(() {
        if(widget.params != null) {
          _params = widget.params;
          _status = widget.params["status"];
        }
        HqGetOrderDataForStatus(_status);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: sWidth(6)),
      child: Stack(
        children: [
          Column(
            children: [
              _orderInfo('货运名称', _params["name"]),
              SizedBox(height: sHeight(4),),
              _orderInfo('货运单价', _params["price"]),
              SizedBox(height: sHeight(4),),
              _orderInfo('发货时间', _params["time"]),
              SizedBox(height: sHeight(4),),
              !isShowDriver ? Container() :
              Column(
                children: [
                  _orderInfo('承载司机', _params["driver"], phone: _params["phone"]),
                  SizedBox(height: sHeight(4),),
                  _orderInfo('承载车辆', _params["carNumber"]),
                ],
              )
            ],
          ),
          !isShowRecharge ? Container() :
          Positioned(
            right: sWidth(6),
            bottom: sHeight(0),
            child: Column(
              children: [
                HQCircleButtonWidget(
                    bgColor: Colors.white,
                    lineColor: Color.fromRGBO(23, 127, 243, 1.0),
                    insets: EdgeInsets.only(left: sWidth(6), top: sHeight(2), right: sWidth(6), bottom: sHeight(2)),
                    widget: Text('更换', style: TextStyle(fontSize: sFontSize(12), color: Color.fromRGBO(23, 127, 243, 1.0)),),
                    onTap: () {HqOrderButtonCallback(HqOrderButtonType.Driver, conversation: widget.conv);}
                ),
                SizedBox(height: sHeight(10),),
                HQCircleButtonWidget(
                    bgColor: Colors.white,
                    lineColor: Color.fromRGBO(23, 127, 243, 1.0),
                    insets: EdgeInsets.only(left: sWidth(6), top: sHeight(2), right: sWidth(6), bottom: sHeight(2)),
                    widget: Text('更换', style: TextStyle(fontSize: sFontSize(12), color: Color.fromRGBO(23, 127, 243, 1.0)),),
                    onTap: () {HqOrderButtonCallback(HqOrderButtonType.Car, conversation: widget.conv);}
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  /// 通用order信息info
  _orderInfo(String tip, String info, {String phone}) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('${tip}：',
          style: TextStyle(
              fontSize: sFontSize(14),
              color: Color.fromRGBO(153, 153, 153, 1.0)),),
        (phone == null || phone == '') ? Text(info,
          style: TextStyle(
              fontSize: sFontSize(14),
              color: Color.fromRGBO(96, 105, 114, 1.0)),) :
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(info,
              style: TextStyle(
                  fontSize: sFontSize(14),
                  color: Color.fromRGBO(96, 105, 114, 1.0)),),
            Text(phone,
              style: TextStyle(
                  fontSize: sFontSize(14),
                  color: Color.fromRGBO(96, 105, 114, 1.0)),),
          ],
        )
      ],
    );
  }
}

/// 底部按钮区
class HqOrderButtonFromMessage extends StatefulWidget {

  final Map<String, String> params;
  final EMConversation conv;
  HqOrderButtonFromMessage(this.params, EMConversation conversation) : conv = conversation;

  @override
  _HqOrderButtonFromMessageState createState() => _HqOrderButtonFromMessageState();
}

class _HqOrderButtonFromMessageState extends State<HqOrderButtonFromMessage> {

  String _status;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _initParams();
  }

  @override
  void didUpdateWidget(covariant HqOrderButtonFromMessage oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);

    _initParams();
  }

  _initParams() {
    if(mounted) {
      setState(() {
        if(widget.params != null) {
          _status = widget.params["status"];
        }
        HqGetOrderDataForStatus(_status);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return !isShowBottom ? Container() :
    Container(
      padding: EdgeInsets.only(top: sHeight(10), right: sWidth(6)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          leftButton == '' ? Container() :
          HQCircleButtonWidget(
              bgColor: Colors.white,
              lineColor: Color.fromRGBO(151, 151, 151, 1.0),
              insets: EdgeInsets.only(left: sWidth(7), top: sHeight(3.5), right: sWidth(7), bottom: sHeight(3.5)),
              widget: Text(leftButton, style: TextStyle(fontSize: sFontSize(14), color: Color.fromRGBO(96, 105, 114, 1.0)),),
              onTap: () { HqOrderButtonCallback(lbuttonType, conversation: widget.conv); }
          ),
          !isShowRightButton ? Container() :
          Row(
            children: [
              SizedBox(width: sWidth(4),),
              HQCircleButtonWidget(
                  bgColor: Color.fromRGBO(23, 127, 243, 1.0),
                  lineColor: Color.fromRGBO(23, 127, 243, 1.0),
                  insets: EdgeInsets.only(left: sWidth(7), top: sHeight(3.5), right: sWidth(7), bottom: sHeight(3.5)),
                  widget: Text(rightButton, style: TextStyle(fontSize: sFontSize(14), color: Colors.white),),
                  onTap: () { HqOrderButtonCallback(rbuttonType, conversation: widget.conv); }
              )
            ],
          ),
        ],
      ),
    );
  }
}

/// 公共方法
HqOrderButtonCallback(HqOrderButtonType buttonType, {EMConversation conversation}) {
  switch(buttonType) {
    case HqOrderButtonType.Driver:
      print('更换司机');
      break;
    case HqOrderButtonType.Car:
      print('更换车辆');
      break;
    case HqOrderButtonType.RefuseOrder:
      print('拒绝接单');
      break;
    case HqOrderButtonType.SureSend:
      print('确认送达');
      break;
    case HqOrderButtonType.GetAllOrder:
      print('查看全部运单');
      break;
    case HqOrderButtonType.GetAllCar:
      print('查看全部车辆');
      break;
    case HqOrderButtonType.ContactCustomer:
      print('联系客服');
      break;
    case HqOrderButtonType.SeeOrderDetail:
      print('查看详情');
      break;
    case HqOrderButtonType.SureReceiveOrder:
      print('确认接单');
      if(conversation != null) {
        IMHelper.updateCustomMessage(conversation);
      }
      break;
    case HqOrderButtonType.GoEvaluate:
      print('去评价');
      break;
  }
}

HqGetOrderDataForStatus(String status) {
  switch(status) {
    case '0':
      isShowStatus = false;
      isShowRecharge = true;
      isShowBottom = true;
      isShowDriver = true;
      isShowRightButton = true;
      orderNum = '请您确认运单信息';
      leftButton = '拒绝接单';
      rightButton = '确认接单';
      lbuttonType = HqOrderButtonType.RefuseOrder;
      rbuttonType = HqOrderButtonType.SureReceiveOrder;
      break;
    case '1':
      isShowStatus = true;
      isShowRecharge = false;
      isShowBottom = true;
      isShowDriver = true;
      isShowRightButton = true;
      orderNum = 'YD74636363545454';
      leftButton = '';
      rightButton = '确认送达';
      statusName = '运输中';
      rbuttonType = HqOrderButtonType.SureSend;
      statusColor = Color.fromRGBO(0, 201, 195, 1.0);
      break;
    case '2':
      isShowStatus = true;
      isShowRecharge = false;
      isShowBottom = false;
      isShowDriver = true;
      isShowRightButton = false;
      orderNum = 'YD74636363545454';
      statusName = '待结算';
      statusColor = Color.fromRGBO(23, 127, 243, 1.0);
      break;
    case '3':
      isShowStatus = true;
      isShowRecharge = false;
      isShowBottom = true;
      isShowDriver = true;
      isShowRightButton = true;
      statusName = '待结算';
      leftButton = '';
      rightButton = '去评价';
      orderNum = 'YD74636363545454';
      statusColor = Color.fromRGBO(23, 127, 243, 1.0);
      rbuttonType = HqOrderButtonType.GoEvaluate;
      break;
    case '4':
      isShowStatus = true;
      isShowRecharge = false;
      isShowBottom = false;
      isShowDriver = true;
      isShowRightButton = false;
      statusName = '已拒绝';
      orderNum = '运单信息';
      statusColor = Color.fromRGBO(255, 93, 93, 1.0);
      break;
    case '5':
      isShowStatus = true;
      isShowRecharge = true;
      isShowBottom = false;
      isShowDriver = true;
      isShowRightButton = false;
      statusName = '已失效';
      orderNum = '运单信息';
      statusColor = Color.fromRGBO(161, 165, 169, 1.0);
      break;
    case '6':
      isShowStatus = false;
      isShowRecharge = false;
      isShowRightButton = false;
      isShowDriver = false;
      isShowBottom = true;
      leftButton = '查看详情';
      orderNum = '我转发了一个运单';
      lbuttonType = HqOrderButtonType.SeeOrderDetail;
      break;
    case '7':
      isShowStatus = false;
      isShowRecharge = false;
      isShowDriver = false;
      isShowBottom = true;
      isShowRightButton = true;
      leftButton = '查看详情';
      rightButton = '确认接单';
      orderNum = '张三分享了一个运单';
      lbuttonType = HqOrderButtonType.SeeOrderDetail;
      rbuttonType = HqOrderButtonType.SureReceiveOrder;
      break;
  }
}

/// order按钮
enum HqOrderButtonType {
  Driver,  /// 更换司机
  Car,  /// 更换车辆
  RefuseOrder, /// 拒绝接单
  GetAllOrder, /// 查看全部运单
  GetAllCar, /// 查看全部车辆
  ContactCustomer, /// 联系客服
  SureSend, /// 确认送达
  GoEvaluate, /// 去评价
  SeeOrderDetail, /// 查看详情
  SureReceiveOrder, /// 确认接单
}